package com.example.wsappproject.MvpDemo.Data;

import com.example.wsappproject.Util.HandlerUtil;
import com.example.wsappproject.Util.OkHttpUtil;
import com.example.wsappproject.constant.ApiInterface;
import com.example.wsappproject.practice.ArticleEntity;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class RemoteDataSource implements IDataSource {
    @Override
    public void articleList(int currentPage, final NetCallBack<ArticleEntity> netCallBack) {

        String url = String.format(Locale.CHINA, ApiInterface.ARTICLE_URL,currentPage);
        OkHttpUtil.enqueue(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                final ArticleEntity articleEntity = new Gson().fromJson(result,ArticleEntity.class);
                HandlerUtil.post(new Runnable() {
                    @Override
                    public void run() {
                        netCallBack.onResponse(articleEntity);
                    }
                });
            }
        });
    }

    private static RemoteDataSource INSTANCE;
    private RemoteDataSource(){

    }
    public static RemoteDataSource getInstance(){
        if (INSTANCE == null){
            INSTANCE = new RemoteDataSource();
        }
        return INSTANCE;
    }
}
